﻿using System;
using System.IO;
using System.Xml;
using BuzzX8.Xmpp.StreamElements;

namespace BuzzX8.Xmpp
{
    public class XmppStreamWriter : IDisposable
    {
        private StreamWriter streamWriter;
        private XmlWriter xmlWriter;

        private bool autoFlush = true;
        private bool disposed = false;
        private bool closeXmlWriter;

        public XmppStreamWriter(Stream stream)
        {
            xmlWriter = CreateXmlWriter(stream);
            closeXmlWriter = true;
        }

        public XmppStreamWriter(XmlWriter xmlWriter)
        {
            this.xmlWriter = xmlWriter;
            closeXmlWriter = false;
        }

        public bool AutoFlush
        {
            get { return autoFlush; }
            set { autoFlush = value; }
        }

        private XmlWriter CreateXmlWriter(Stream stream)
        {
            streamWriter = new StreamWriter(stream);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            
            return XmlWriter.Create(streamWriter, settings);
        }

        public void Flush()
        {
            xmlWriter.Flush();
        }

        public void Write(StreamElement element)
        {
            ThrowExceptionIfDisposed();
            element.Write(xmlWriter);
            if (AutoFlush) Flush();
        }

        private void ThrowExceptionIfDisposed()
        {
            if (disposed) throw new ObjectDisposedException("XmppStreamWriter");
        }

        public void Close()
        {
            Dispose();
        }

        public void Dispose()
        {
            if (disposed) return;
            if (closeXmlWriter) xmlWriter.Close();
            streamWriter.Dispose();
            disposed = true;
        }
    }
}
